<template>
  <div class="editor-wrapper border">
    <Toolbar
      :class="['toolbar', props.staticToolBar ? 'static-toolbar' : 'dynamic-toolbar']"
      ref="toolbar"
      v-show="showToolbar"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      class="editor"
      ref="editor"
      :modelValue="curValue"
      :defaultConfig="editorConfig"
      @onCreated="onCreated"
      @onChange="onChange"
      @onBlur="onBlur"
      @onFocus="onFocus"
      :mode="mode"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import './styles/reset-wangeditor.scss'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ref, shallowRef, onBeforeMount, watch } from 'vue'

const emit = defineEmits(['input', 'onFocus', 'change', 'blur'])
const model = defineModel()
const props = defineProps({
  'staticToolBar': {
    type: Boolean,
    default: false
  }, 
  'toolbarKeys': {
    type: Array,
    default: () => {
      return [
        'color', // 字体色
        'bgColor', // 背景色
        'bold',
        'insertLink', // 链接
      ]
    }
  }
})

const curValue = ref('')
const editorRef = shallowRef()
const showToolbar = ref(props.staticToolBar || false)

const mode = 'simple'

const toolbarConfig = {
  toolbarKeys: props.toolbarKeys
  // [
  //   'color', // 字体色
  //   'bgColor', // 背景色
  //   'bold',
  //   'insertLink', // 链接
  //   'uploadImage',
  //   'fontSize',
  //   'justifyLeft', 
  //   'justifyCenter', 
  //   'justifyRight',
  // ]
}

const editorConfig = {MENU_CONF: {}}
editorConfig.MENU_CONF['uploadImage'] = {
  server: window.$app.fileUploadUrl,
  // timeout: 5 * 1000, // 5s

  fieldName: 'file',
  meta: { 
    unZip: true,
    frameNum: 1,
    userId: window.$app.user.userId
  },
  metaWithUrl: false, // join params to url
  headers: {  
    branchCode: window.$app.user.branchCode,
    'X-Client-Language': 'zh_CN',
    'Access-Token': window.$app.user.token,
    'X-User-Account': window.$app.user.userId 
  },

  maxFileSize: 10 * 1024 * 1024, // 10M

  base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb

  onBeforeUpload(file) {
    // console.log('onBeforeUpload', file)

    return file // will upload this file
    // return false // prevent upload
  },
  customInsert(res, insertFn) {
    // console.log('customInsert', res)
    const imgInfo = res?.fileInfos[0] || {}
    const { localPath, fileName } = imgInfo
    if (!localPath) throw new Error(`Image url is empty`)

    // console.log('Your image url ', localPath)
    insertFn(window.$app.fileBaseUrl + localPath, fileName, window.$app.fileBaseUrl + localPath)
  },
  // onProgress(progress) {
  //   console.log('onProgress', progress)
  // },
  // onSuccess(file, res) {
  //   console.log('onSuccess---', file, res)
  // },
  // onFailed(file, res) {
  //   console.log('onFailed---', file, res)
  // },
  // onError(file, err, res) {
  //   console.error('onError---', file, err, res)
  // },

  // customInsert(res, insertFn) {
  //   console.log('customInsert', res)
  //   const imgInfo = res.data[0] || {}
  //   const { url, alt, href } = imgInfo
  //   if (!url) throw new Error(`Image url is empty`)

  //   console.log('Your image url ', url)
  //   insertFn(url, alt, href)
  // },

  // customUpload(file, insertFn) {
  //   console.log('customUpload', file)

  //   return new Promise((resolve) => {
  //     // Simulate async insert image
  //     setTimeout(() => {
  //       const src = `https://www.baidu.com/img/flexible/logo/pc/result@2.png?r=${Math.random()}`
  //       insertFn(src, 'baidu logo', src)
  //       resolve('ok')
  //     }, 500)
  //   })
  // },

  // customBrowseAndUpload(insertFn) {
  //   alert('Custom browse and upload')

  //   // Simulate async insert image
  //   setTimeout(() => {
  //     const src = 'https://www.baidu.com/img/flexible/logo/pc/result@2.png'
  //     insertFn(src, 'baidu logo', src) // insert a image
  //   }, 500)
  // },
}

const setHtml = (newHtml) => {
  const editor = editorRef.value
  if (editor == null) return
  editor.setHtml(newHtml)
}

const onCreated = (editor) => {
  editorRef.value = editor
  if (model.value) {
    setHtml(model.value)
  }
}
const onChange = (editor) => {
  const editorHtml = editor.getHtml()
  curValue.value = editorHtml // 记录当前 html 内容
  emit('input', editorHtml) // 用于自定义 v-model
}
const onFocus = (editor) => {
  emit('onFocus', editor)
  setToolbarStatus(true)
}
const onBlur = (editor) => {
  const editorHtml = editor.getHtml()
  curValue.value = editorHtml // 记录当前 html 内容
  emit('change', editorHtml)
  emit('blur', editor)
  setToolbarStatus(false)
}

const setToolbarStatus = (status) => {
  if (props.staticToolBar) return
  showToolbar.value = status
}

watch(
  () => model.value,
  (newVal) => {
    // console.log('watch', newVal)
    const isEqual = newVal === curValue.value
    if (isEqual) return // 和当前内容一样，则忽略
// console.log('watch', newVal)
    // 重置 HTML
    setHtml(newVal)
  },
  {
    // immediate: true
  }
)

onBeforeMount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
</script>
<style lang="scss" scoped>
.editor-wrapper {
  position: relative;
  width: 100%;
  // min-height: 45px;
}

.static-toolbar {
  border-bottom: 1px solid #dedede;
}
.dynamic-toolbar {
  position: absolute;
  left: 0;
  top: -44px;
}

.editor {
  padding: 10px 0;
  // padding: 0;
}

.border {
  border-radius: 2px;

  &:hover {
    box-shadow: none; // 0 0 4px 0 rgb(255 192 62 / 36%);
  }
}
</style>
